package com.buaa.aimall.userModule.Controller;

import com.alibaba.fastjson.JSONObject;
import com.buaa.aimall.Utils.BaseResponse;
import com.buaa.aimall.Utils.Config.JeepayConfig;
import com.buaa.aimall.Utils.Enum.StatusCode;
import com.buaa.aimall.Utils.PageReturnResult;
import com.buaa.aimall.goodsModule.Service.CouponService;
import com.buaa.aimall.goodsModule.Service.TransactionOrderService;
import com.buaa.aimall.userModule.DTO.PageDTO;
import com.buaa.aimall.userModule.DTO.RechargeDTO;
import com.buaa.aimall.userModule.Entity.RechargePayOrderEntity;
import com.buaa.aimall.userModule.Entity.UserEntity;
import com.buaa.aimall.userModule.Enum.PayOrderStatusEnum;
import com.buaa.aimall.userModule.Service.JeepayService;
import com.buaa.aimall.userModule.Service.RechargePayOrderService;
import com.buaa.aimall.userModule.Service.UserService;
import com.jeequan.jeepay.response.PayOrderCreateResponse;
import com.jeequan.jeepay.response.PayOrderQueryResponse;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/user/wallet")
@CrossOrigin
public class WalletController {
    @Autowired
    private UserService userService;

    @Autowired
    private RechargePayOrderService rechargePayOrderService;

    @Autowired
    private JeepayService jeepayService;

    private final JeepayConfig jeepayConfig;

    @Autowired
    private TransactionOrderService transactionOrderService;

    @Autowired
    private CouponService couponService;

    @Autowired
    public WalletController(JeepayConfig jeepayConfig) {
        this.jeepayConfig = jeepayConfig;
    }

    @PostMapping("/recharge")
    public BaseResponse<PayOrderCreateResponse> recharge(@RequestBody RechargeDTO rechargeDTO) {
        UserEntity user = userService.getCurrentUser();

        PayOrderCreateResponse response = jeepayService.recharge(rechargeDTO.getAmount(), user);

        if (response == null) {
            return new BaseResponse<>(StatusCode.DAO_ERROR, "向支付网关请求失败", null);
        }
        if (!response.checkSign(jeepayConfig.getApiKey())) {
            return new BaseResponse<>(StatusCode.CHECK_SIGN_FAILED, "支付网关响应验签失败", response);
        }
        if (!response.isSuccess(jeepayConfig.getApiKey())) {
            return new BaseResponse<>(StatusCode.PAY_FAILED, "支付网关创建订单失败", response);
        }

        RechargePayOrderEntity rechargePayOrder = RechargePayOrderEntity.builder()
                .user(user.getId())
                .mchOrderNo(response.getData().getString("mchOrderNo"))
                .amount(rechargeDTO.getAmount())
                .status(PayOrderStatusEnum.PAYMENT_IN_PROGRESS)
                .build();
        rechargePayOrderService.save(rechargePayOrder);

        return new BaseResponse<>(StatusCode.SUCCESS, "发起充值订单成功", response);
    }

    @PostMapping("filter-recharge-pay-order")
    public BaseResponse<PageReturnResult<RechargePayOrderEntity>> FilterRechargePayOrder(@RequestBody PageDTO pageDTO) {
        UserEntity user = userService.getCurrentUser();
        var result = rechargePayOrderService.getPageByUserId(user.getId(), pageDTO);
        return new BaseResponse<>(StatusCode.SUCCESS, "获取充值订单列表成功", result);
    }

    @PostMapping("query-pay-order")
    public BaseResponse<PayOrderQueryResponse> queryPayOrder(@RequestBody Map<String, Object> requestBody) {
        PayOrderQueryResponse response = jeepayService.query((String) requestBody.get("mchOrderNo"));
        return new BaseResponse<>("查询充值订单明细", response != null && response.isSuccess(jeepayConfig.getApiKey()), response);
    }

    @GetMapping("financial-center")
    public BaseResponse<JSONObject> financialCenter() {
        UserEntity user = userService.getCurrentUser();
        JSONObject jsonObject = new JSONObject();

        long unpaidOrderCount = transactionOrderService.getUnpaidCount(user.getId());
        int amountToday = transactionOrderService.getPaymentAmountTodayOrThisMonth(user.getId(), true);
        int amountThisMonth = transactionOrderService.getPaymentAmountTodayOrThisMonth(user.getId(), false);
        long couponCount = couponService.getCountByUser(user.getId());

        jsonObject.put("balance", user.getBalance());
        jsonObject.put("isVerified", StringUtils.isNotBlank(user.getIdcard()));
        jsonObject.put("unpaidOrderCount", unpaidOrderCount);
        jsonObject.put("amountToday", amountToday);
        jsonObject.put("amountThisMonth", amountThisMonth);
        jsonObject.put("couponCount", couponCount);
        return new BaseResponse<>(StatusCode.SUCCESS, "查询财务中心信息成功", jsonObject);
    }
}
